// src/main/java/com/example/tracing/interceptor/TraceIdInterceptor.java
package com.ybw.interceptor;

import com.ybw.config.TraceIdProperties;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 处理HTTP请求的拦截器，用于在请求处理之前和处理之后添加和移除traceId
 *
 * @author ybw
 * @version V1.0
 * @className TraceIdInterceptor
 * @date 2024/4/13
 **/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TraceIdInterceptor implements HandlerInterceptor {

    @Resource
    private TraceIdProperties traceIdProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取traceId
        String traceId = getTraceId(request);
        //2、将traceId放入MDC
        MDC.put(traceIdProperties.getHeaderName(), traceId);
        //3、将traceId放入响应头
        response.setHeader(traceIdProperties.getHeaderName(), traceId);
        return true;
    }

    /**
     * 获取traceId
     *
     * @param request
     * @methodName: getTraceId
     * @return: java.lang.String
     * @author: ybw
     * @date: 2024/4/13
     **/
    public String getTraceId(HttpServletRequest request) {
        String traceId = request.getHeader(traceIdProperties.getHeaderName());
        if (traceId != null && !traceId.isEmpty()) {
            return traceId;
        }
        // 如果请求头中没有traceId，您可以在此处生成一个随机的traceId
        return UUID.randomUUID().toString();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.remove(traceIdProperties.getHeaderName());
    }
}